package com.push.web.service.impl;

import com.push.common.utils.DateUtils;
import com.push.common.utils.StringUtils;
import com.push.web.domain.BizArticle;
import com.push.web.mapper.BizArticleMapper;
import com.push.web.mapper.BizCollectionMapper;
import com.push.web.service.IBizArticleService;
import com.push.web.service.IBizOCRService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * OCRService业务层处理
 *
 * @author yanxi
 * @date 2022-03-10
 */
@Service
public class BizOCRServiceImpl implements IBizOCRService
{

    /**
     * 解析传入过来的URL
     *
     * @param URL字符串
     * @return 解析之后的列表
     */
    @Override
    public List<String> parseURL(String URL) {
        // 打印URL
        System.out.println(URL);

        List<String> results = parseURLFun(URL);
        for (String line : results) {
            System.out.println(line);
        }

        return results;
    }

    public static List<String> parseURLFun(String URL) {
        List<String> result = new ArrayList<>();
        try {
            ProcessBuilder pb = new ProcessBuilder("python", "parse.py", URL);
            Process p = pb.start();

            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.add(line);
            }
            in.close();

            BufferedReader errorReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            while ((line = errorReader.readLine()) != null) {
                System.out.println("Error: " + line);
            }
            errorReader.close();

            int exitCode = p.waitFor();
            if (exitCode == 0) {
                System.out.println("Script executed successfully.");
            } else {
                System.out.println("Script execution failed with exit code: " + exitCode);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return result;
    }
}

